﻿namespace MicroCloud.Filter
{
    /// <summary>
    /// 筛选条件组
    /// </summary>
    public class FilterGroup
    {
        #region 构造函数
        /// <summary>
        /// 初始化一个筛选条件组 <see cref="FilterGroup"/> 的新实例
        /// </summary>
        public FilterGroup()
            : this(FilterOperate.And)
        { }
        
        /// <summary>
        /// 初始化一个筛选条件组 <see cref="FilterGroup"/> 的新实例
        /// </summary>
        /// <param name="operateCode">条件间操作方式的前台码</param>
        public FilterGroup(string operateCode)
            : this(FilterHelper.GetFilterOperate(operateCode))
        { }

        /// <summary>
        /// 使用操作方式初始化一个筛选条件组 <see cref="FilterGroup"/> 的新实例
        /// </summary>
        /// <param name="operate">条件间操作方式</param>
        public FilterGroup(FilterOperate operate)
        {
            Operate = operate;
            Rules = new List<FilterRule>();
            Groups = new List<FilterGroup>();
        }

        #endregion

        #region 属性
        /// <summary>
        /// 获取或设置 条件集合
        /// </summary>
        public ICollection<FilterRule> Rules { get; set; }

        /// <summary>
        /// 获取或设置 条件组集合
        /// </summary>
        public ICollection<FilterGroup> Groups { get; set; }
        
        #region "获取或设置 条件间操作方式，仅限 And、Or 。"
        private FilterOperate _Operate;
        /// <summary>
        /// 获取或设置 条件间操作方式
        /// <para>仅限 And、Or 。</para>
        /// </summary>
        public FilterOperate Operate
        {
            get { return _Operate; }
            set
            {
                if (value != FilterOperate.And && value != FilterOperate.Or)
                {
                    var errMsg = I18N.T(Resources.Filter_GroupOperateError);
                    throw new InvalidOperationException(errMsg);
                }
                _Operate = value;
            }
        }
        #endregion

        #endregion      

        #region 方法
        /// <summary>
        /// 添加规则
        /// </summary>
        /// <param name="rule"></param>
        /// <returns></returns>
        public FilterGroup AddRule(FilterRule rule)
        {
            if (Rules.All(m => !m.Equals(rule)))
            {
                Rules.Add(rule);
            }
            return this;
        }

        /// <summary>
        /// 添加规则
        /// </summary>
        /// <param name="field"></param>
        /// <param name="value"></param>
        /// <param name="operate"></param>
        /// <returns></returns>
        public FilterGroup AddRule(string field, object value, FilterOperate operate = FilterOperate.Equal)
        {
            FilterRule rule = new(field, value, operate);
            return AddRule(rule);
        }

        #endregion

    }

}
